<template>
  <div>
    <!-- 
          inline：行内表单，一行可放多个
    -->
    <el-form :inline="true" class="demo-form-inline" :model="cForm">
      <el-form-item label="一级分类">
        <el-select placeholder="请选择" v-model="cForm.c1Id" @change="getC2List(cForm.c1Id)" :disabled="show">
          <el-option v-for="c1 in list1" :key="c1.id" :label="c1.name" :value="c1.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="cForm.c2Id" @change="getC3List(cForm.c2Id)" :disabled="show">
          <el-option v-for="c2 in list2" :key="c2.id" :label="c2.name" :value="c2.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="cForm.c3Id" @change="getInfoList()" :disabled="show">
          <el-option v-for="c3 in list3" :key="c3.id" :label="c3.name" :value="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategorySelect',
  // 接收父组件传来的show
  props: ['show'],
  data() {
    return {
      list1: [],
      list2: [],
      list3: [],
      cForm: {
        c1Id: '',
        c2Id: '',
        c3Id: ''
      }
    }
  },
  // 挂载完毕，即获取一级分类
  mounted() {
    // 获取一级分类数据
    this.getCategoryList()
  },
  methods: {
    // 各级分类的事件回调
    async getCategoryList() {
      const result = await this.$API.attr.reqCategory1List()
      if (result.code === 200) {
        this.list1 = result.data
      }
    },
    async getC2List(id) {
      this.list2 = []
      this.list3 = []
      this.cForm.c2Id = ''
      this.cForm.c3Id = ''
      // 向父组件发射对应的一级id
      this.$emit('getCategoryId', { cId: this.cForm.c1Id, level: 1 })

      const result = await this.$API.attr.reqCategory2List(id)
      if (result.code === 200) {
        this.list2 = result.data
      }
    },
    async getC3List(id) {
      this.list3 = []
      this.cForm.c3Id = ''
      // 向父组件发射对应的二级id
      this.$emit('getCategoryId', { cId: this.cForm.c2Id, level: 2 })

      const result = await this.$API.attr.reqCategory3List(id)
      if (result.code === 200) {
        this.list3 = result.data
      }
    },
    // 三级分类选定后，将id传给父组件，以确定显示哪些数据
    getInfoList() {
      // 向父组件发射对应的三级id
      this.$emit('getCategoryId', { cId: this.cForm.c3Id, level: 3 })
    }
  }
}
</script>

<style>
</style>